package thinkingInJava.generics;
// page 420 泛型潜在类型机制的实现(反射)
// 两个完全不相关的类,可能会有几个相同签名的函数,那么就可以写一个通用方法(只调用相同的函数)来同时操作这两个类
// C++ 中普通泛型本来就支持这种模式,但 java 不行,需要用另外的方法来实现.
//: generics/LatentReflection.java
//Using Reflection to produce latent typing.
import java.lang.reflect.*;
import static thinkingInJava.YTool.YPrint.*;

class Robot{};

//Does not implement Performs:
class Mime {
public void walkAgainstTheWind() {}
public void sit() { print("Pretending to sit"); }
public void pushInvisibleWalls() {}
public String toString() { return "Mime"; }
}

//Does not implement Performs:
class SmartDog {
public void speak() { print("Woof!"); }
public void sit() { print("Sitting"); }
public void reproduce() {}
}	

class CommunicateReflectively {
public static void perform(Object speaker) {
 Class<?> spkr = speaker.getClass();
 try {
   try {
     Method speak = spkr.getMethod("speak");
     speak.invoke(speaker);
   } catch(NoSuchMethodException e) {
     print(speaker + " cannot speak");
   }
   try {
     Method sit = spkr.getMethod("sit");
     sit.invoke(speaker);
   } catch(NoSuchMethodException e) {
     print(speaker + " cannot sit");
   }
 } catch(Exception e) {
   throw new RuntimeException(speaker.toString(), e);
 }
}
}

public class LatentReflection {
public static void main(String[] args) {
 CommunicateReflectively.perform(new SmartDog());
 CommunicateReflectively.perform(new Robot());
 CommunicateReflectively.perform(new Mime());	// 有个优于 C++的是, Mine 虽然没有 speak, 但仍然可以调用 sit
}
} /* Output:
Woof!
Sitting
Click!
Clank!
Mime cannot speak
Pretending to sit
*///:~

